package com.xdemo.algorithm;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CommonShortUrlGenerator implements IShortUrlGenerator {

	private MessageDigest digest;
	
	private final char[] seeds = {
			'a','b','c','d','e','f','g','h',
			'i','j','k','l','m','n','o','p',
			'q','r','s','t','u','v','w','x',
			'y','z','0','1','2','3','4','5',
			'6','7','8','9','9','8','7','6',
			'5','4','3','2','1','0','a','b',
			'c','d','e','f','g','h','i','j',
			'k','l','m','n','o','p','q','r'
	};
		
	public CommonShortUrlGenerator() {
		try {
			this.digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public String shortUrl(String url) {
		byte[] _md5 = digest.digest(url.getBytes());
		int[] _mid = new int[32];
		for(int i=0;i<16;i++) {
			_mid[2*i] = (_md5[i] & 0xFF ) >> 2;
			_mid[2*i+1] = _md5[i] & 0x3F;
		}
		char[] _midalpha = new char[32];
		for(int i=0;i<32;i++) {
			_midalpha[i] = seeds[_mid[i]];
		}
		char[] _result = new char[8];
		for(int i=0;i<8;i++) {
			_result[i] = _midalpha[i*4 + (int)(Math.random() * 4)];
		}
		return new String(_result);
	}

}
